<?php
/*
 * Created on Sep 8, 2012
 *
 * To change the template for this generated file go to
 * Window - Preferences - PHPeclipse - PHP - Code Templates
 */

include_once("utils/CouponUtils.php");
include_once("utils/CommonUtils.php");

include_once("domain/LinkDomain.php");
include_once("domain/AdvertiserDomain.php");

include_once("domain/MerchantDomain.php");
include_once("domain/CouponImageDomain.php");

include_once("obj/GanCouponLink.php");

include_once("impl/CouponImpl.php");
include_once("impl/MerchantImpl.php");
include_once("impl/AdvertiserImpl.php");


class FeedImpl extends CommonUtils
{
	private $couponImpl;
	private $merImpl;
	private $adImpl;
	private $catImpl;
	
	private $ga;
	
	private $isAddNewMer;
	private $DbTagFeed;
	
	function __construct($DBTag, $DbTagFeed)
	{
		parent::__construct();
		
		$this->DBTag 		= $DBTag;
		$this->DbTagFeed	= $DbTagFeed;
		
		$this->couponImpl 	= new CouponImpl($DBTag);
		$this->merImpl 		= new MerchantImpl($DBTag);
		$this->adImpl 		= new AdvertiserImpl($DBTag);
		$this->catImpl 		= new CategoryImpl($DBTag);
		
		$this->ga 			= new GoogleAffiliateApi();
		$this->ga->init();
	}	
	
	public function addCoupon($link)
	{
		$oMer 		= $this->merImpl->getByAdvertiserId(GlobalConstant::SOURCE_ID_GOOGLE, $link->getAdvertiserId());
		
		$id			= 0;
		$oCat 		= false;
		$advertiser	= false;
		$this->isAddNewMer = false;
		
		// find merchant by alias
		if(!is_object($oMer)){
			$adv = $this->ga->getAdvertiser(GlobalConstant::SOURCE_ID_GOOGLE, $link->getAdvertiserId());			
			
			if(is_object($adv)){
				$oMer = $this->merImpl->getByAlias($adv->getName());
				
				if(!is_object($oMer)){
					$oMer = $this->merImpl->getByName($adv->getName());
				}
			}
		}
		
		if(is_object($oMer)){					
			$adverCatName 	= $this->merImpl->getAdvertiserCategory(GlobalConstant::SOURCE_ID_GOOGLE, $link->getAdvertiserId());
			
			if(empty($adverCatName)){
				if(!is_object($adv))
					$adv = $this->ga->getAdvertiser($link->getAdvertiserId());
				
				if(is_object($adv)){		
					$this->adImpl->updateMerchantByGooglAdvertiser($oMer, $adv);
				}
			}
			
			$adverCatName 	= $this->merImpl->getAdvertiserCategory(GlobalConstant::SOURCE_ID_GOOGLE, $link->getAdvertiserId());
		}else{
			if(!is_object($adv)){
				$adv = $this->ga->getAdvertiser($link->getAdvertiserId());
			}
			
			echo "merchant is empty.";
			echo "\n";
			
			if(is_object($adv)){
				echo "need add new merchant, linkId : " . $link->getId();
				echo "\n";
				echo "need add new merchant, AdvertiserId : " . $link->getAdvertiserId();
				echo "\n";
				
				$oMer = $this->adImpl->addMerchantByGooglAdvertiser($adv);
				
				if(is_object($oMer)){
					$this->isAddNewMer = true;
					$this->getNewMerchantInfo($link, $adv, $oMer);

					$adverCatName 	= $this->merImpl->getAdvertiserCategory(GlobalConstant::SOURCE_ID_GOOGLE, $link->getAdvertiserId());
				}
			}

		}
		

		
		if(!empty($adverCatName))
			$oCat = $this->catImpl->getCategoryByAlias($adverCatName);
		
		if(!is_object($oCat)){
			echo "category id requested.";
			echo "\n";
			
			echo "AdvertiserId : " . $link->getAdvertiserId();
			echo "\n";
			
			echo "adverCatName : $adverCatName";
			echo "\n";
			
			if(is_object($oMer)){
				echo "merchant id : " . $oMer->getId();
				echo "\n";
			}else{
				echo "merchant miss";
				echo "\n";
			}
			
			return -1;
		}
		
		
		if(is_object($oMer)){			
			$name	= $link->getName();
			
			// filter name
			if ($link->getPromotionType() == 'coupon'){
				$name 	= StringUtils::getStartValue(' with coupon code', $name);
			}
		
			$code	= $link->getPromotionCodes();
			
			//convert creative type
			$creativeType 	= 0;
			$width			= 0;
			$height			= 0;
			
			// parse code from coupon name
			if(empty($code)){
				$code = CouponUtils::findCode($name);
			}
			
			// filter link name
			$pattern[0] = "/(\d+)x(\d+)/i";
			$pattern[1] = "/(\d+) x (\d+)/i";

			$replacement 	= '';
			$filtername 	= preg_replace($pattern[0], $replacement, $name);
			$filtername 	= preg_replace($pattern[1], $replacement, $filtername);
			$filtername 	= str_ireplace ('banner', $replacement, $filtername);
//			$filtername 	= str_ireplace (' logo', $replacement, $filtername);
//			$filtername 	= str_ireplace (' Logo', $replacement, $filtername);
			
			$filtername 	= trim($filtername, ' ');
			$filtername 	= trim($filtername, '-');
			$filtername 	= trim($filtername, '_');
			$filtername 	= trim($filtername, ' ');
			
			$description 	= $link->getDescription();
			
			$similar 		= 0;
			similar_text($filtername, $description, $similar);
			
			if($description == $link->getName() || number_format($similar, 0) > 90)
				$description = '';
			
			$cd = new CouponDomain();
			
			if($link->getLinkType() == 'BANNER'){
				$creativeType = '1';
				
				$imgInfo = $this->getImageInfo($link->getImpressionTrackingUrl());
				
				$width	= $imgInfo['width'];
				$height	= $imgInfo['height'];
				
				if($imgInfo['isValid']){
								
				$couponImg = new CouponImageDomain();
				
				$couponImg->setName($filtername);
				$couponImg->setWidth($width);
				$couponImg->setHeight($height);				
				$couponImg->setImpressionTrackingUrl($link->getImpressionTrackingUrl());
				$couponImg->setImageAltText($link->getImageAltText());
				$couponImg->setUseType('0');
				$couponImg->setStatus('1');
				
				$cd->setCouponImage($couponImg);
					
				}else{
					$creativeType = '2';// image size too small , convert type to text
				}
			}else if ($link->getLinkType() == 'TEXT'){
				$creativeType = '2';
			}else
				return -1;		
			
			$cd->setName($filtername);
			$cd->setDescript($description);
			$cd->setStartDate($link->getStartDate());
			$cd->setEndDate($link->getEndDate());
			$cd->setCreateDate($link->getCreateDate());
			
			$cd->setCreativeType($creativeType);
			$cd->setMerchantId($oMer->getId());
		
			$cd->setCode($code);
			$cd->setCostType(GlobalConstant::COST_TYPE_CPA);
			
			$cd->setTrackingURL($link->getClickTrackingUrl());
			
			$cd->setSourceId(GlobalConstant::SOURCE_ID_GOOGLE);
			$cd->setStatus(1);			
			
			
			$id = $this->couponImpl->add($cd);
			
			
			
			if($cd->getId() > 0){
//				echo "\n";
//				echo "coupon id: " . $cd->getId();
//				echo "\n";
//				
				
				// add category of coupon
				if(is_object($oCat)){
					$this->couponImpl->addCategory($cd->getId(), $oCat->getId());
				}
				
				// add attributes
				$attributeIdForPromoType = $this->getAttributeIdForPromoType($link->getPromotionType(), $link->getName());
				
				$this->couponImpl->addAttribute($cd->getId(), 64, $link->getId());
				
				if($attributeIdForPromoType > 0){
					$this->couponImpl->addAttribute($cd->getId(), 62, $attributeIdForPromoType);
				}
				
				$isFreeShipping = $link->getFreeShipping();
				if(!empty($isFreeShipping)){
					$this->couponImpl->addAttribute($cd->getId(), 2, $isFreeShipping);
				}
				
				$freeShippingMinAmount = $link->getFreeShippingMinAmount();
				if($freeShippingMinAmount > 0){
					$this->couponImpl->addAttribute($cd->getId(), 58, $freeShippingMinAmount);
				}
				
				$percentOff = $link->getPercentOff();
				if($percentOff > 0){
					$this->couponImpl->addAttribute($cd->getId(), 1, $percentOff);
				}
				
				$percentOffMinAmount = $link->getPercentOffMinAmount();
				if($percentOffMinAmount > 0){
					$this->couponImpl->addAttribute($cd->getId(), 60, $percentOffMinAmount);
				}
				
				$freeGift = $link->getFreeGift();
				if($freeGift > 0){
					$this->couponImpl->addAttribute($cd->getId(), 37, $freeGift);
				}
				
				$priceCutAmount = $link->getPriceCutAmount();
				if($priceCutAmount > 0){
					$this->couponImpl->addAttribute($cd->getId(), 54, $priceCutAmount);
				}
			}
		}else{
			echo "merchant miss.";
			echo "\n";
			
			echo "AdvertiserId : " . $link->getAdvertiserId();
			echo "\n";
			
			return -1;
		}
		
		return $id;
	}
	
	public function addCjCouponLinkToCoupon($link, $merId)
	{		
		$name	= $link->getFilterName();		
		if(empty($name)){
			$this->message = 'filter coupon name is empty. Original coupon name: ' . $name;

			return -1;
		}
			
		$catId	= $this->getCategoryId($link->category);
		
		if(empty($catId)){
			$this->message = 'not found catogory by ' . $link->category;

			return -1;
		}
		
		$code			= $link->getCode();
		$description 	= $link->getFilterDescription();
		
		//convert creative type
		$creativeType 	= 0;
		$width			= 0;
		$height			= 0;		
		
		$cd = new CouponDomain();
		
		if($link->linkType == 'Banner'){
			$creativeType = '1';
			
			$bannerUrl = $link->getBannerUrl();
			
			if(!empty($bannerUrl)){
				$imgInfo = $this->getImageInfo($bannerUrl);
				
				$width	= $imgInfo['width'];
				$height	= $imgInfo['height'];
				
				if($imgInfo['isValid']){							
					$couponImg = new CouponImageDomain();
					
					$couponImg->setName($name);
					$couponImg->setWidth($width);
					$couponImg->setHeight($height);				
					$couponImg->setImpressionTrackingUrl($bannerUrl);
					$couponImg->setImageAltText('');
					$couponImg->setUseType('0');
					$couponImg->setStatus('1');
					
					$cd->setCouponImage($couponImg);
					
				}else{
					$creativeType = '2';// image size too small , convert type to text
				}
			}else
				$creativeType = '2';// not found image src url , convert type to text
		}else if ($link->linkType == 'Text Link'){
			$creativeType = '2';
		}else
			return -1;		
		
		$cd->name				= $name;
		$cd->descript			= $description;
		$cd->startDate			= $link->promotionStartDate;
		$cd->endDate			= $link->promotionEndDate;
		$cd->createDate			= $link->promotionStartDate;
		
		$cd->creativeType		= $creativeType;
		$cd->merchantId			= $merId;
	
		$cd->code				= $code;
		$cd->costType			= GlobalConstant::COST_TYPE_CPA;
		
		$cd->trackingHtmlCode  	= $link->linkCodeHtml;
		$cd->linkCodeJavascript = $link_->linkCodeJavascript;
		
		$cd->impressionpixel	= $link->getImpressionPixelUrl();
		$cd->trackingURL		= $link->getTrackingUrl();
		
		$cd->sourceId 			= GlobalConstant::SOURCE_ID_CJ;
		$cd->status				= '1';	
		
		
		$id = $this->couponImpl->add($cd);
		
//		echo "\n coupon id: " . $cd->getId();
//		echo "\n";

		
		if($cd->getId() > 0){
			// add category of coupon
			if(!empty($catId)){
				$this->couponImpl->addCategory($cd->getId(), $catId);
			}
			
			// add attributes
			$this->couponImpl->addAttribute($cd->getId(), 64, $link->linkId);
			
			
			$attributeIdForPromoType = $this->getAttributeIdForCjPromoType($link->promotionType, $link->linkName);
			if($attributeIdForPromoType > 0){
				$this->couponImpl->addAttribute($cd->getId(), 62, $attributeIdForPromoType);
			}
			
			$sevenDayEpc = $link->sevenDayEpc;
			if(!empty($sevenDayEpc)){
				$this->couponImpl->addAttribute($cd->getId(), 66, $sevenDayEpc);
			}
			
			$threeMonthEpc = $link->threeMonthEpc;
			if($threeMonthEpc > 0){
				$this->couponImpl->addAttribute($cd->getId(), 67, $threeMonthEpc);
			}
			
			$saleCommission = $link->saleCommission;
			if($saleCommission > 0){
				$this->couponImpl->addAttribute($cd->getId(), 70, $saleCommission);
			}
		}
		
		$this->message = $this->couponImpl->getMessage();
		 
		return $id;
	}
	
	public function addGanCouponLinkToCoupon($link, $merId, $catId)
	{		
		$name	= $this->filterGanCouponName($link->name);		
		if(empty($name)){
			$this->message = 'filter coupon name is empty. Original coupon name: ' . $link->name;

			return -1;
		}
		
		$code			= $this->filterGanCouponCode($link);
		$description 	= $this->filterGanCouponDescription($link);
		
		//convert creative type
		$creativeType 	= 0;
		$width			= 0;
		$height			= 0;		
		
		$cd = new CouponDomain();
		
		if($link->linkType == 'BANNER'){
			$creativeType = '1';
			
			$imgInfo = $this->getImageInfo($link->impressionTrackingUrl);
			
			$width	= $imgInfo['width'];
			$height	= $imgInfo['height'];
			
			if($imgInfo['isValid']){							
				$couponImg = new CouponImageDomain();
				
				$couponImg->setName($name);
				$couponImg->setWidth($width);
				$couponImg->setHeight($height);				
				$couponImg->setImpressionTrackingUrl($link->impressionTrackingUrl);
				$couponImg->setImageAltText($link->imageAltText);
				$couponImg->setUseType('0');
				$couponImg->setStatus('1');
				
				$cd->setCouponImage($couponImg);
				
			}else{
				$creativeType = '2';// image size too small , convert type to text
			}
		}else if ($link->linkType == 'TEXT'){
			$creativeType = '2';
		}else
			return -1;		
		
		$cd->setName($name);
		$cd->setDescript($description);
		$cd->setStartDate($link->startDate);
		$cd->setEndDate($link->endDate);
		$cd->setCreateDate($link->createDate);
		
		$cd->setCreativeType($creativeType);
		$cd->setMerchantId($merId);
	
		$cd->setCode($code);
		$cd->setCostType(GlobalConstant::COST_TYPE_CPA);
		
		$cd->setTrackingURL($link->clickTrackingUrl);
		
		$cd->setSourceId(GlobalConstant::SOURCE_ID_GOOGLE);
		$cd->setStatus(1);			
		
		
		$id = $this->couponImpl->add($cd);
		
//		echo "<br>";
//		echo "coupon id: " . $cd->getId();
//		echo "<br>";

		
		if($cd->getId() > 0){
			// add category of coupon
			if(!empty($catId)){
				$this->couponImpl->addCategory($cd->getId(), $catId);
			}
			
			// add attributes
			$attributeIdForPromoType = $this->getAttributeIdForPromoType($link->promotionType, $link->name);
			
			$this->couponImpl->addAttribute($cd->getId(), 64, $link->linkId);
			
			if($attributeIdForPromoType > 0){
				$this->couponImpl->addAttribute($cd->getId(), 62, $attributeIdForPromoType);
			}
			
			$isFreeShipping = $link->soFreeShipping;
			if(!empty($isFreeShipping)){
				$this->couponImpl->addAttribute($cd->getId(), 2, $isFreeShipping);
			}
			
			$freeShippingMinAmount = $link->sofsmAmount;
			if($freeShippingMinAmount > 0){
				$this->couponImpl->addAttribute($cd->getId(), 58, $freeShippingMinAmount);
			}
			
			$percentOff = $link->soPercentOff;
			if($percentOff > 0){
				$this->couponImpl->addAttribute($cd->getId(), 1, $percentOff);
			}
			
			$percentOffMinAmount = $link->sopomAmount;
			if($percentOffMinAmount > 0){
				$this->couponImpl->addAttribute($cd->getId(), 60, $percentOffMinAmount);
			}
			
			$freeGift = $link->soFreeGift;
			if($freeGift > 0){
				$this->couponImpl->addAttribute($cd->getId(), 37, $freeGift);
			}
			
			$priceCutAmount = $link->sopcAmount;
			if($priceCutAmount > 0){
				$this->couponImpl->addAttribute($cd->getId(), 54, $priceCutAmount);
			}
		}
		
		
		return $id;
	}
	
	public function addGanCouponLinkToDB($link, $categoryId)
	{
		$oMer = $this->merImpl->getByAdvertiserId(GlobalConstant::SOURCE_ID_GOOGLE, $link->advertiserId);		
		
		// find merchant by alias
		if(!is_object($oMer)){
			$this->message 	= "not found mapping merchant in DB. advertiser id : " . $link->advertiserId;
			
			return -1;
		}
		
		//convert creative type
		$creativeType 	= 0;
		
		$name	= $this->filterGanCouponName($link->name);		
		if(empty($name)){
			$this->message = 'filter coupon name is empty. Original coupon name: ' . $link->name;
			
			return -1;
		}
		
		$code	= $link->soPromoCodes;		
		if(empty($code)){
			$code = CouponUtils::findCode($name); // parse code from coupon name
		}		
		
		$description 	= $this->filterGanCouponDescription($name, $link->impressionTrackingUrl);
		
		// create coupon object for DB
		$cd = new CouponDomain();
			
		if($link->linkType == 'BANNER'){
			$creativeType = '1';
			
			$imgInfo = $this->getImageInfo($link->impressionTrackingUrl);
			
			$width	= $imgInfo['width'];
			$height	= $imgInfo['height'];
			
			if($imgInfo['isValid']){								
				$couponImg = new CouponImageDomain();
				
				$couponImg->setName($name);
				$couponImg->setWidth($width);
				$couponImg->setHeight($height);				
				$couponImg->setImpressionTrackingUrl($link->impressionTrackingUrl);
				$couponImg->setImageAltText($link->imageAltText);
				$couponImg->setUseType('0');
				$couponImg->setStatus('1');
				
				$cd->setCouponImage($couponImg);						
			}else{
				$creativeType = '2';// image size too small , convert type to text
			}
		}else if ($link->linkType == 'TEXT'){
			$creativeType = '2';
		}else{
			$this->message = 'skip this link type: ' . $link->linkType;
			return -1;		
		}
		
		$cd->setName($name);
		$cd->setCode($code);
		$cd->setDescript($description);
		$cd->setStartDate($link->startDate);
		$cd->setEndDate($link->endDate);
		$cd->setCreateDate($link->createDate);
		
		$cd->setMerchantId($oMer->getId());	
		
		$cd->setCostType(GlobalConstant::COST_TYPE_CPA);
		$cd->setSourceId(GlobalConstant::SOURCE_ID_GOOGLE);
		
		$cd->setCreativeType($creativeType);
		$cd->setTrackingURL($link->clickTrackingUrl);
		
		$cd->setStatus(1);			
		
		
		$id = $this->couponImpl->add($cd);		
		if($cd->getId() > 0){
//			echo "\n";
//			echo "coupon id: " . $cd->getId();
//			echo "\n";
//				
				
			// add category of coupon
			$this->couponImpl->addCategory($cd->getId(), $categoryId);
			
			// add attributes			
			$this->addGanNumberAttribute($cd->getId(), 64, $link->linkId);			
			
			$this->addGanNumberAttribute($cd->getId(), 2, $link->soFreeShipping);			
			$this->addGanNumberAttribute($cd->getId(), 1, $link->soPercentOff);			
			$this->addGanNumberAttribute($cd->getId(), 37, $link->soFreeGift);
			
			$this->addGanNumberAttribute($cd->getId(), 54, $link->sopcAmount);
			$this->addGanNumberAttribute($cd->getId(), 60, $link->sopomAmount);
			$this->addGanNumberAttribute($cd->getId(), 58, $link->sofsmAmount);
			
			$this->addGanNumberAttribute($cd->getId(), 66, $link->esdaAmount);
			$this->addGanNumberAttribute($cd->getId(), 67, $link->endaAmount);
			
			if($link->endaAmount > 0)
				$this->couponImpl->addAttribute($cd->getId(), 65, $link->endaCurrencyCode);
			
			if($link->esdaAmount > 0)
				$this->couponImpl->addAttribute($cd->getId(), 68, $link->esdaCurrencyCode);
			
			$attributeIdForPromoType = $this->getAttributeIdForPromoType($link->promotionType, $name);
			$this->addGanNumberAttribute($cd->getId(), 62, $attributeIdForPromoType);			
			
		}else{
			$this->message = $this->couponImpl->getMessage();
		}		
		
		return $id;
	}	
	
	public function addGanCouponFeeds($ganLinks, $requestApiTime)
	{
		$conn 	= $this->getConnection($this->DbTagFeed);
		
		foreach($ganLinks as $ganLink){
			if($ganLink instanceof LinkDomain){
				$sql 	 = "INSERT INTO gan_coupon_links SET ";
				
				$sql 	.= " linkId=";
				$sql	.= addslashes($ganLink->getId());
	
				$sql 	.= ", kind='";
				$sql	.= addslashes($ganLink->getKind());
	
				$sql 	.= "', isActive='";
				$sql	.= $ganLink->getIsActive();
				
				$sql 	.= "', name='";
				$sql	.= addslashes($ganLink->getName());
					
				$sql 	.= "', advertiserId=";
				$sql	.= $ganLink->getAdvertiserId();
		
				$sql 	.= ", destinationUrl='";
				$sql	.= addslashes($ganLink->getDestinationUrl());
				$sql	.= "'";
	
				$startDate = $ganLink->getStartDate();
				if(!empty($startDate)){
					$sql	.= ", startDate='";
					$sql	.= date('Y-m-d H:i:s', strtotime($startDate));
					$sql	.= "'";
				}
				
				$endDate = $ganLink->getEndDate();
				if(!empty($endDate)){
					$sql	.= ", endDate='";
					$sql	.= date('Y-m-d H:i:s', strtotime($endDate));
					$sql	.= "'";
				}
				
				$createDate = $ganLink->getCreateDate();
				if(!empty($createDate)){
					$sql	.= ", createDate='";
					$sql	.= date('Y-m-d H:i:s', strtotime($createDate));
					$sql	.= "'";
				}
							
				$descript = $ganLink->getDescription();
				if(!empty($descript)){
					$sql	.= ", description='";
					$sql	.= addslashes($descript);
					$sql	.= "'";
				}
				
				$sql	.= ", imageAltText='";
				$sql	.= addslashes($ganLink->getImageAltText());
	
				$sql	.= "', availability='";
				$sql	.= $ganLink->getAvailability();
	
				$sql	.= "', authorship='";
				$sql	.= $ganLink->getAuthorship();
	
				$sql	.= "', promotionType='";
				$sql	.= $ganLink->getPromotionType();
				$sql	.= "'";
				
				$sql	.= ", duration='";
				$sql	.= $ganLink->getDuration();
				$sql	.= "'";
				
				$sql	.= ", impressionTrackingUrl='";
				$sql	.= addslashes($ganLink->getImpressionTrackingUrl());
				$sql	.= "'";
				
				$sql	.= ", clickTrackingUrl='";
				$sql	.= addslashes($ganLink->getClickTrackingUrl());
				$sql	.= "'";
				
				$sql	.= ", linkType='";
				$sql	.= $ganLink->getLinkType();
				$sql	.= "'";
				
				$sql	.= ", esdaAmount='";
				$sql	.= $ganLink->getEpcSevenDayAverageAmount();
				$sql	.= "'";
				
				$sql	.= ", esdaCurrencyCode='";
				$sql	.= $ganLink->getEpcSevenDayAverageCurrencyCode();
				$sql	.= "'";
				
				$sql	.= ", endaAmount='";
				$sql	.= $ganLink->getEpcNinetyDayAverageAmount();
				$sql	.= "'";
				
				$sql	.= ", endaCurrencyCode='";
				$sql	.= $ganLink->getEpcNinetyDayAverageCurrencyCode();
				$sql	.= "'";
				
				$sql	.= ", soPromoCodes='";
				$sql	.= addslashes($ganLink->getPromotionCodes());
				$sql	.= "'";
				
				$sql	.= ", soPercentOff='";
				$sql	.= $ganLink->getPercentOff();
				$sql	.= "'";
				
				$sql	.= ", sopomAmount='";
				$sql	.= $ganLink->getPercentOffMinAmount();
				$sql	.= "'";
				
				$sql	.= ", sopomCurrencyCode='";
				$sql	.= $ganLink->getPercentOffMinCurrencyCode();
				$sql	.= "'";
				
				$sql	.= ", sopcAmount='";
				$sql	.= $ganLink->getPriceCutAmount();
				$sql	.= "'";
				
				$sql	.= ", sopcCurrencyCode='";
				$sql	.= $ganLink->getPriceCutCurrencyCode();
				$sql	.= "'";
				
				$sql	.= ", sopcmAmount='";
				$sql	.= $ganLink->getPriceCutMinAmount();
				$sql	.= "'";
				
				$sql	.= ", sopcmCurrencyCode='";
				$sql	.= $ganLink->getPriceCutMinCurrencyCode();
				$sql	.= "'";
				
				$sql	.= ", soFreeShipping='";
				$sql	.= $ganLink->getFreeShipping();
				$sql	.= "'";
				
				$sql	.= ", sofsmAmount='";
				$sql	.= $ganLink->getFreeShippingMinAmount();
				$sql	.= "'";
				
				$sql	.= ", sofsmCurrencyCode='";
				$sql	.= $ganLink->getFreeShippingMinCurrencyCode();
				$sql	.= "'";
				
				$sql	.= ", soFreeGift='";
				$sql	.= $ganLink->getFreeGift();
							
				$sql	.= "', requestApiTime='";
				$sql	.= $requestApiTime;
				$sql	.= "' ON DUPLICATE KEY UPDATE requestApiTime=Values(requestApiTime), isActive=Values(isActive), soFreeGift=Values(soFreeGift)," .
						"sofsmCurrencyCode=Values(sofsmCurrencyCode), sofsmAmount=Values(sofsmAmount), soFreeShipping=Values(soFreeShipping), sopcmCurrencyCode=Values(sopcmCurrencyCode), " .
						"sopcmAmount=Values(sopcmAmount), sopcCurrencyCode=Values(sopcCurrencyCode), sopcAmount=Values(sopcAmount), sopomCurrencyCode=Values(sopomCurrencyCode), " .
						"sopomAmount=Values(sopomAmount), soPercentOff=Values(soPercentOff), soPromoCodes=Values(soPromoCodes), endaCurrencyCode=Values(endaCurrencyCode), " .
						"endaAmount=Values(endaAmount), esdaCurrencyCode=Values(esdaCurrencyCode), esdaAmount=Values(esdaAmount), linkType=Values(linkType), " .
						"clickTrackingUrl=Values(clickTrackingUrl), impressionTrackingUrl=Values(impressionTrackingUrl), duration=Values(duration), " .
						"promotionType=Values(promotionType), authorship=Values(authorship), availability=Values(availability), " .
						"imageAltText=Values(imageAltText), description=Values(description), createDate=Values(createDate), startDate=Values(startDate), " .
						"endDate=Values(endDate), destinationUrl=Values(destinationUrl), advertiserId=Values(advertiserId), name=Values(name), kind=Values(kind)";
				
				$id		= 0;

//				echo $sql;
				try{					
					$rs  	= mysql_query($sql, $conn) or die("<br><br>Invalid query: " . $sql . mysql_error($conn));
					
					if($rs){
						$id = mysql_insert_id($conn);
						
						$this->messages = "add successfully. id = $id";
					}else{
						$this->messages  = "add failed. sql : $sql . <br>";
						$this->messages .= "error: " .  mysql_error($conn);
					}
				}catch(Exception $e){
					$this->messages = $e->getMessage();
					
					$id	= -1;
				}
				
			}else{
				$id	= -1;
				
				$this->message = 'input object is not instance of LinkDomain.';
			}	
		}
		
		$this->freeConnection($this->DbTagFeed, $conn);
			
		return $id;
	}
	
	private function addGanNumberAttribute($couponId, $attributeId, $attributeValue)
	{
		if($attributeValue > 0){
			$this->couponImpl->addAttribute($couponId, $attributeId, $attributeValue);
		}
	}	
	
	public function getGanCouponFeed($linkId)
	{
		$conn		= null;	
		
		try{
			$conn 	= $this->getConnection($this->DbTagFeed);
			
			$sql  = 'SELECT id, linkId, advertiserId, name, isActive, destinationUrl, description, linkType, startDate, endDate, imageAltText, ';
			$sql .= "availability, authorship, promotionType, duration, createDate, impressionTrackingUrl, clickTrackingUrl, " .
					"esdaAmount, esdaCurrencyCode, endaAmount, endaCurrencyCode, soPromoCodes, soPercentOff, sopomAmount, sopomCurrencyCode " .
					", sopcAmount, sopcCurrencyCode, sopcmAmount, sopcmCurrencyCode, soFreeShipping, sofsmAmount, sofsmCurrencyCode" .
					",soFreeGift, requestApiTime, r_recommend FROM gan_coupon_links WHERE linkId = $linkId";
				
			$rs  = mysql_query($sql, $conn);
			
			if($row = mysql_fetch_array($rs)){
				$obj = new GanCouponLink();

				$obj->id					= $row[0];
				$obj->linkId 				= $row[1];
				$obj->advertiserId 			= $row[2];
				$obj->name					= $row[3];
				$obj->isActive				= $row[4];
						
				$obj->destinationUrl		= $row[5];
				$obj->description			= $row[6];
				
				$obj->linkType				= $row[7];
				$obj->startDate				= $row[8];
				$obj->endDate				= $row[9];
				
				$obj->imageAltText			= $row[10];
				$obj->availability			= $row[11];						
				$obj->authorship			= $row[12];
				
				$obj->promotionType			= $row[13];
				$obj->duration				= $row[14];						
				$obj->createDate			= $row[15];
				
				$obj->impressionTrackingUrl	= $row[16];						
				$obj->clickTrackingUrl		= $row[17];						
				$obj->esdaAmount			= $row[18];						
				$obj->esdaCurrencyCode		= $row[19];
						
				$obj->endaAmount			= $row[20];
				$obj->endaCurrencyCode		= $row[21];
				$obj->soPromoCodes			= $row[22];
				$obj->soPercentOff			= $row[23];
				$obj->sopomAmount			= $row[24];

				$obj->sopomCurrencyCode		= $row[25];
				$obj->sopcAmount			= $row[26];
				$obj->sopcCurrencyCode		= $row[27];
				$obj->sopcmAmount			= $row[28];
				$obj->sopcmCurrencyCode		= $row[29];
				$obj->soFreeShipping		= $row[30];
				
				$obj->sofsmAmount			= $row[31];
				$obj->sofsmCurrencyCode		= $row[32];
				$obj->soFreeGift			= $row[33];
 
 				$obj->r_requestApiTime		= $row[34];
 				$obj->r_recommend			= $row[35];
 				
 				$obj->r_couponId			= 0;

			}
		}catch(Exception $e){
			$this->message = $e->getMessage();			
		}
		
		$this->freeConnection($this->DbTagFeed, $conn);
		return $obj;
	}
	
	public function getGanCouponFeedCustoms($where, $order, $page = 0, $discount = 20)
	{
		$arrback 	= array();
		$conn		= null;	
		
		try{
			$conn 	= $this->getConnection($this->DbTagFeed);
			
			$sql 	= "SELECT count(1) FROM gan_coupon_links $where";
			$rs  	= mysql_query($sql, $conn);
			
			list($total) = mysql_fetch_row($rs);
			
			$this->mutilPager($total, $page, $discount);
			if(!empty($total)){
				$sql  = 'SELECT id, linkId, advertiserId, name, isActive, destinationUrl, description, linkType, startDate, endDate, imageAltText, ';
				$sql .= "availability, authorship, promotionType, duration, createDate, impressionTrackingUrl, clickTrackingUrl, " .
						"esdaAmount, esdaCurrencyCode, endaAmount, endaCurrencyCode, soPromoCodes, soPercentOff, sopomAmount, sopomCurrencyCode " .
						", sopcAmount, sopcCurrencyCode, sopcmAmount, sopcmCurrencyCode, soFreeShipping, sofsmAmount, sofsmCurrencyCode" .
						",soFreeGift, requestApiTime, r_recommend FROM gan_coupon_links $where $order";
				
				if($discount > 0)
					$sql .= " LIMIT $this->firstcount, $discount";
				
				$rs  = mysql_query($sql, $conn) or die("<br><br>Invalid query: " . $sql . mysql_error($conn));
				if($rs){
					while($row = mysql_fetch_array($rs)){
						$obj = new GanCouponLink();

						$obj->id					= $row[0];
						$obj->linkId 				= $row[1];
						$obj->advertiserId 			= $row[2];
						$obj->name					= $row[3];
						$obj->isActive				= $row[4];
						
						$obj->destinationUrl		= $row[5];
						$obj->description			= $row[6];
						
						$obj->linkType				= $row[7];
						$obj->startDate				= $row[8];
						$obj->endDate				= $row[9];
						
						$obj->imageAltText			= $row[10];
						$obj->availability			= $row[11];						
						$obj->authorship			= $row[12];
						
						$obj->promotionType			= $row[13];
						$obj->duration				= $row[14];						
						$obj->createDate			= $row[15];
						
						$obj->impressionTrackingUrl	= $row[16];						
						$obj->clickTrackingUrl		= $row[17];						
						$obj->esdaAmount			= $row[18];						
						$obj->esdaCurrencyCode		= $row[19];
						
						$obj->endaAmount			= $row[20];
						$obj->endaCurrencyCode		= $row[21];
						$obj->soPromoCodes			= $row[22];
						$obj->soPercentOff			= $row[23];
						$obj->sopomAmount			= $row[24];

						$obj->sopomCurrencyCode		= $row[25];
						$obj->sopcAmount			= $row[26];
						$obj->sopcCurrencyCode		= $row[27];
						$obj->sopcmAmount			= $row[28];
						$obj->sopcmCurrencyCode		= $row[29];
						$obj->soFreeShipping		= $row[30];
						
						$obj->sofsmAmount			= $row[31];
						$obj->sofsmCurrencyCode		= $row[32];
						$obj->soFreeGift			= $row[33];
 
 						$obj->r_requestApiTime		= $row[34];
 						$obj->r_recommend			= $row[35];
 						
 						$obj->r_couponId			= 0;

						$arrback[] = $obj;
					}
				}else {
					$this->message = "select failed. sql : $sql";
					$this->message .= "<br>error: " . mysql_error($conn);

				}
			}
		}catch(Exception $e){
			$this->message = $e->getMessage();			
		}
		
		$this->freeConnection($this->DbTagFeed, $conn);
		return $arrback;
	}
	
	public function getGanCouponIdKeyExisted($merId, $link)
	{
		$name	= $this->filterGanCouponName($link->name);		
		if(empty($name)){			
			return false;
		}
		
		$code			= $this->filterGanCouponCode($link);
		$description 	= $this->filterGanCouponDescription($link);
		
		$couponIdKey	= $this->couponImpl->getCouponIdKey($merId, $code, $name, $description);

		
		return $this->couponImpl->getByIdKey($couponIdKey);
	}
	
	
	public function setRecommend($linkId, $r_recommend) 
	{
		$sql  = "UPDATE gan_coupon_links SET r_recommend = $r_recommend WHERE linkId = $linkId";
		
		return $this->update($this->DbTagFeed, $sql);
	}
	
	private function filterGanCouponCode($link)
	{
		// parse code from coupon name
		$code	= $link->soPromoCodes;
		if(empty($code)){
			$code = CouponUtils::findCode($link->name);
		}
		
		return $code;
	}
	
	private function filterCjCouponCode($link)
	{
		// parse code from coupon name
		$code = CouponUtils::findCode($link->description);		
		
		return $code;
	}
	
	private function filterGanCouponDescription($link)
	{
		$similar 		= 0;
		similar_text($link->name, $link->description, $similar);
			
		if($link->description == $link->name || number_format($similar, 0) > 90)
			return '';
		
		return $link->description;
	}
	
	private function filterCjCouponDescription($link)
	{
		$similar 		= 0;
		similar_text($link->linkName, $link->description, $similar);
			
		if($link->description == $link->linkName || number_format($similar, 0) > 90)
			return '';
		
		return $link->description;
	}
	
	public function filterGanCouponName($name)
	{
		if(StringUtils::count_words($name) < 2)// if words than less 2, ignore this coupon
			return '';
	
		$pos = strripos($name, "logo");
		if($pos > -1){
			return '';
		}
		
		
		$pattern[0] = "/(\d+)x(\d+)/i";
		$pattern[1] = "/(\d+) x (\d+)/i";

		$replacement 	= '';
		$name 	= preg_replace($pattern[0], $replacement, $name);
		$name 	= preg_replace($pattern[1], $replacement, $name);
		$name 	= str_ireplace ('banner', $replacement, $name);
//		$name 	= str_ireplace (' logo', $replacement, $name);
//		$name 	= str_ireplace (' Logo', $replacement, $name);
		
		$name 	= trim($name, ' ');
		$name 	= trim($name, '-');
		$name 	= trim($name, '_');
		$name 	= trim($name, ' ');
		
		return $name;
	}
	
	private function getAttributeIdForCjPromoType($promoTypeName, $couponName)
	{
		$attribteId = 0;
		
		switch ($promoTypeName) {
		    case "coupon":
		        $attribteId = 33; 
		        break;
		    case "sale/discount":
		        $attribteId = 32; 
		        break;
		    case "free shipping":
		        $attribteId = 2; 
		        break;
		    case "seasonal link":
		        $attribteId = 71; 
		        break;    
		        
		}
		
		
		
		return $attribteId;
	}
	
	private function getAttributeIdForPromoType($promoTypeName, $couponName)
	{
		$attribteId = 0;
		
		switch ($promoTypeName) {
		    case "Ongoing Promotion":
		        $attribteId = 31;
		        break;
		    case "Sale":
		       $attribteId = 32; 
		        break;
		    case "Coupon":
		        $attribteId = 33; 
		        break;
		    case "Unspecified":
		        $attribteId = 34; 
		        break;
		    case "Price Cut":
		        $attribteId = 35; 
		        break;
		    case "Product Promotion":
		        $attribteId = 36; 
		        break;
		    case "Free Shipping":
		        $attribteId = 2; 
		        break;
		    case "Percent Off":
		        $attribteId = 1; 
		        break;
		    case "Free Gift":
		        $attribteId = 37; 
		        break;
		    case "Sweepstakes":
		        $attribteId = 38; 
		        break;
		    case "Free Gift Wrap":
		        $attribteId = 39; 
		        break;
		    case "Buy x Get y":
		        $attribteId = 40; 
		        break;
	
		}
		
		if($attribteId == 34){// Unspecified
			$pos1 = strrpos($couponName, '$');
			$pos2 = strrpos($couponName, '%');
			if($pos1 > 0 || $pos2 > 0 || $pos1 === 0 || $pos2 === 0){
				
			}else
				$attribteId = 0;
		}
		
		return $attribteId;
	}
	
	private function getImageInfo($filename)
	{
		$arrinfo 	= array();		
		$imageinfo 	= @getImageSize ($filename);
		
		$arrinfo['isValid'] = 0;
		$arrinfo['width'] 	= $imageinfo[0];
		$arrinfo['height']	= $imageinfo[1];
		$arrinfo['type']	= $imageinfo[2];		
		
		if($arrinfo['width'] > 20 || $arrinfo['height'] > 20){
			$arrinfo['isValid'] = 1;
		}
		
		if(empty($arrinfo['width']))
			$arrinfo['width'] 	= 0;
			
		if(empty($arrinfo['height']))
			$arrinfo['height']	= 0;
		
		return $arrinfo;
	}
	
	public function isAddNewMerchant()
	{
		return $this->isAddNewMer;
	}
	
	
	public function getNewMerchantInfo($link, $adv, $mer)
	{
		$arrinfo = array();
		
		$arrinfo['advertiserId'] 	= $link->getAdvertiserId();
		$arrinfo['advertiserName'] 	= $adv->getName();
		$arrinfo['merchantId'] 		= $mer->getId();
		
		return $arrinfo;
	}
	
	private function getCategoryId($adverCategory)
	{
		$categoryName = ucwords(strtolower(str_ireplace('_', ' ', $adverCategory)));
	
		$oCat = $this->catImpl->getByName($categoryName);
		
		$categoryId = '';
		
		if(is_object($oCat)){
			$categoryId = $oCat->getId();
		}else{
			$oCat = $this->catImpl->getCategoryByAlias($categoryName);
			
			if(is_object($oCat)){
				$categoryId = $oCat->getId();
			}
		}
		
		if(empty($categoryId)){
			$oCat = $this->catImpl->getCategoryByAlias($adverCategory);
			
			if(is_object($oCat)){
				$categoryId = $oCat->getId();
			}
		}
		
//		if(empty($categoryId)){
//			echo "\n";
//			echo "======================= not found category for update merchant ======================================";
//			echo "\n";
//			
//			echo "category Ailas: " . $adverCategory;
//			echo "\n";
//			
//			echo "merchant id: " . $oMer->getId();
//			echo "\n";
//			
//			echo "advertiser id: " . $adv->getId();
//			echo "\n";
//			
//			echo "category : " . $categoryName;
//			echo "\n";
//		
//			echo "\n";
//			echo "\n";
//		}
		
		
		return $categoryId;
	}
}
?>
